package yu.code.yurpc.utils;

import cn.hutool.core.io.resource.NoResourceException;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import yu.code.yurpc.handler.ConfigHandler;
import yu.code.yurpc.handler.PropsHandler;
import yu.code.yurpc.handler.YamlHandler;

/**
 * 配置读取工具
 */
@Slf4j
public class ConfigUtils {
    /**
     * 加载配置对象
     *
     * @param tClass
     * @param prefix
     * @param <T>
     * @return
     */
    public static <T> T loadConfig(Class<T> tClass, String prefix) {
        return loadConfig(tClass, prefix, "");
    }

    private static <T> T loadConfig(Class<T> tClass, String prefix, String environment) {
        StringBuffer configFileBuilder = new StringBuffer("application");
        if (StrUtil.isNotBlank(environment)) {
            configFileBuilder.append("-").append(environment);
        }
        configFileBuilder.append(".");
        ConfigHandler configHandler = null;
        T ret = null;

        if (ret == null) {
            configFileBuilder.replace(configFileBuilder.lastIndexOf("."), configFileBuilder.length(), ".properties");
            configHandler = new PropsHandler();
            try {
                ret = configHandler.loadConfig(tClass, prefix, configFileBuilder.toString());
            } catch (NoResourceException e) {
                log.info(configFileBuilder + " not found");
            }
        }
        if (ret == null) {
            configFileBuilder.replace(configFileBuilder.lastIndexOf("."), configFileBuilder.length(), ".yaml");
            configHandler = new YamlHandler();
            try {
                ret = configHandler.loadConfig(tClass, prefix, configFileBuilder.toString());
            } catch (NoResourceException e) {
                log.info(configFileBuilder + " not found");
            }
        }
        if (ret == null) {
            configFileBuilder.replace(configFileBuilder.lastIndexOf("."), configFileBuilder.length(), ".yml");
            configHandler = new YamlHandler();
            try {
                ret = configHandler.loadConfig(tClass, prefix, configFileBuilder.toString());
            } catch (NoResourceException e) {
                log.info(configFileBuilder + " not found");
                e.printStackTrace();
            }
        }
        return ret;
    }
}
